﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using Flurl.Util;
using System.Net.Http;
using System.Collections.Specialized;

namespace Pay.Service {
    public class SoupTaskService : ServiceBase, ISoupTaskService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMerchantService _iMerchantService;
        private IRedRecordService _redRecordService;
        private ISettingService _iSettingService;
        private IProductService _iProductService;
        private IProductActivityService _iProductActivityService;
        public SoupTaskService(IUnitOfWork iUnitOfWork, IMerchantService iMerchantService, IRedRecordService redRecordService, ISettingService iSettingService, IProductService iProductService
            , IProductActivityService iProductActivityService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            this._iMerchantService = iMerchantService;
            _redRecordService = redRecordService;
            _iSettingService = iSettingService;
            _iProductService = iProductService;
            _iProductActivityService = iProductActivityService;
        }

        #region 后台任务管理
        /// <summary>
        /// 获得任务列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<soup_task_dto> GetSoupTasks(SoupTaskQuery query) {
            var filter = PredicateBuilder.True<SoupTask>();
            if (!string.IsNullOrEmpty(query.title))
                filter = filter.And(c => c.Title == query.title);
            if (!string.IsNullOrEmpty(query.status)) {
                int value = int.Parse(query.status);
                filter = filter.And(c => c.Status == (ESoupTaskStatus)value);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                DateTime time = DateTime.Parse(query.begin_time);
                filter = filter.And(c => c.CreateTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                DateTime time = DateTime.Parse(query.end_time).AddDays(1);
                filter = filter.And(c => c.CreateTime <= time);
            }
            var result = context.SoupTask.FromCachePaged<SoupTask, soup_task_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(c => c.Status).ThenBy(o => o.Sort));
            return result;
        }

        /// <summary>
        /// 获得任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public soup_task_dto GetSoupTask(long id) {
            return context.SoupTask.Find(id).ToDtoObject<soup_task_dto>();
        }

        /// <summary>
        /// 新增任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResultMessage<int> AddSoupTask(soup_task_dto dto) {
            if (context.SoupTask.Exist(o => o.Type == dto.type))
                return new ResultMessage<int>(501, "所选任务已存在，不能重复添加");
            if (string.IsNullOrEmpty(dto.prompt))
                dto.prompt = null;
            dto.create_time = DateTime.Now;
            SoupTask model = new SoupTask();
            dto.ToDtoObject(model);
            context.SoupTask.Add(model);
            int result = _iUnitOfWork.Commit("SoupTask");
            return ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result);
        }

        /// <summary>
        /// 更新任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResultMessage<int> UpdateSoupTask(soup_task_dto dto) {
            if (string.IsNullOrEmpty(dto.prompt))
                dto.prompt = null;
            SoupTask model = context.SoupTask.FindById(dto.id);
            if (model.Type != dto.type && context.SoupTask.Exist(o => o.Type == dto.type))
                return new ResultMessage<int>(501, "所选任务已存在，不能重复添加");
            dto.ToDtoObject(model);
            int result = _iUnitOfWork.Commit("SoupTask");
            return ResultToJson.Json(result > 0 ? " 保存成功" : "未做任何修改", result);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteSoupTask(long id) {
            var model = context.SoupTask.FindById(id);
            context.SoupTask.Remove(model);
            int result = _iUnitOfWork.Commit("SoupTask");
            return result;
        }

        /// <summary>
        /// 修改任务状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int UpdateSoupTaskStatus(long id, int status) {
            SoupTask model = context.SoupTask.FindById(id);
            model.Status = (ESoupTaskStatus)(status);
            int result = _iUnitOfWork.Commit("SoupTask");
            return result;
        }
        #endregion

        /// <summary>
        /// 用户完成任务记录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<user_soup_value_his_dto> GetUserSoupValueHiss(UserSoupValueHisQuery query) {
            var filter = PredicateBuilder.True<UserSoupValueHis>();
            if (!string.IsNullOrEmpty(query.task_type_value)) {
                int value = int.Parse(query.task_type_value);
                filter = filter.And(c => c.TaskType == (ETaskType)value);
            }
            if (!string.IsNullOrEmpty(query.name)) {
                filter = filter.And(o => o.Merchant.Name == query.name);
            }
            if (!string.IsNullOrEmpty(query.mobile)) {
                filter = filter.And(o => o.Merchant.Mobile == query.mobile);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                var time = DateTime.Parse(query.begin_time).ToUnix();
                filter = filter.And(c => c.CreateTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                var time = DateTime.Parse(query.end_time).AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime <= time);
            }
            var result = context.UserSoupValueHis.FromCachePaged<UserSoupValueHis, user_soup_value_his_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(o => o.CreateTime));
            return result;
        }

        /// <summary>
        /// 根据类型获取任务
        /// </summary>
        /// <param name="taskType"></param>
        /// <returns></returns>
        public soup_task_dto GetSoupTaskByType(ETaskType taskType) {
            return context.SoupTask.Where(o => o.Type == taskType).FirstOrDefault().ToDtoObject<soup_task_dto>();
        }

        /// <summary>
        /// app 任务列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<task_dto> GetTaskList(long userId) {
            var list = context.SoupTask.Where(s => s.Category == ESoupTaskCategory.Based || s.Category == ESoupTaskCategory.Exclusive).Where(s => s.Status == ESoupTaskStatus.AdvanceOnline || s.Status == ESoupTaskStatus.Normal).OrderBy(s => s.Sort)
                .FromCache<SoupTask, task_dto>("SoupTask");
            if (userId > 0) {
                foreach (var item in list) {
                    if (item.type == ETaskType.Login) {
                        long startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskDayLogin.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.Maker) {
                        var taskupgrade = context.TokenTaskUpgrade.Find(userId);
                        item.is_complete = (taskupgrade != null && taskupgrade.Status == 2);
                    } else if (item.type == ETaskType.MaYiBuLuo) {
                        long startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskMayi.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.CreditCard) {
                        bool ishas = context.TokenTaskCreditCard.Exist(s => s.UserId == userId && (s.Status == 1 || s.Status == 3));
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.ApplyLoan) {
                        bool ishas = context.TokenTaskApplyLoan.Exist(s => s.UserId == userId && (s.Status == 1 || s.Status == 3));
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.InviteRegister) {
                        var redRecod = _redRecordService.GetUser(userId);
                        bool ishas = (item.limit_num != null && item.limit_num <= redRecod.invitation_num);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.WatchLive) {
                        var startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskWatchLive.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.ViewMall) {
                        var startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskViewMall.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.FollowPubAccount) {
                        var vx = context.WXVerificationCode.Exist(o => o.UserId == userId);
                        item.is_complete = vx;
                    } else if (item.type == ETaskType.Auth) {
                        var member = _iMerchantService.GetTokenUser(userId);
                        item.is_complete = member.is_verify_no_card;
                    } else if (item.type == ETaskType.OpenTokenSupplier) {
                        var merchant = _iMerchantService.Get(userId);
                        item.is_complete = merchant.is_supplier;
                    } else {
                        if (item.limit_num != null && item.limit_num <= context.UserSoupValueHis.Where(s => s.UserId == userId && s.TaskType == item.type).Count())
                            item.is_complete = true;
                    }
                }

                ////已开通节点商城的不显示对应任务
                //var openSupplierTask = list.Where(o => o.type == ETaskType.OpenTokenSupplier && o.is_complete == true).FirstOrDefault();
                //if (openSupplierTask != null)
                //    list.Remove(openSupplierTask);
            }
            return list;
        }

        public List<task_dto> GetTaskList(task_query query) {
            var filter = PredicateBuilder.True<SoupTask>();
            if (query.is_type) filter = filter.And(s => s.IsAppStoreShow == true);
            var list = context.SoupTask.Where(filter).Where(s => s.Category == ESoupTaskCategory.Based || s.Category == ESoupTaskCategory.Exclusive).Where(s => s.Status == ESoupTaskStatus.AdvanceOnline || s.Status == ESoupTaskStatus.Normal).OrderBy(s => s.Sort)
                .FromCache<SoupTask, task_dto>("SoupTask");
            long userId = query.user_id;
            if (userId > 0) {
                foreach (var item in list) {
                    if (item.type == ETaskType.Login) {
                        long startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskDayLogin.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.Maker) {
                        var taskupgrade = context.TokenTaskUpgrade.Find(userId);
                        item.is_complete = (taskupgrade != null && taskupgrade.Status == 2);
                    } else if (item.type == ETaskType.MaYiBuLuo) {
                        long startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskMayi.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.CreditCard) {
                        bool ishas = context.TokenTaskCreditCard.Exist(s => s.UserId == userId && (s.Status == 1 || s.Status == 3));
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.ApplyLoan) {
                        bool ishas = context.TokenTaskApplyLoan.Exist(s => s.UserId == userId && (s.Status == 1 || s.Status == 3));
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.InviteRegister) {
                        var redRecod = _redRecordService.GetUser(userId);
                        bool ishas = (item.limit_num != null && item.limit_num <= redRecod.invitation_num);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.WatchLive) {
                        var startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskWatchLive.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.ViewMall) {
                        var startTime = DateTime.Now.Date.ToUnixInt();
                        bool ishas = context.TokenTaskViewMall.Exist(s => s.Time == startTime && s.UserId == userId);
                        item.is_complete = ishas;
                    } else if (item.type == ETaskType.FollowPubAccount) {
                        var vx = context.WXVerificationCode.Exist(o => o.UserId == userId);
                        item.is_complete = vx;
                    }  else if (item.type == ETaskType.Auth) {
                        var member = _iMerchantService.GetTokenUser(userId);
                        item.is_complete = member.is_verify_no_card;
                    } else if (item.type == ETaskType.OpenTokenSupplier) {
                        var merchant = _iMerchantService.Get(userId);
                        item.is_complete = merchant.is_supplier;
                    } else {
                        if (item.limit_num != null && item.limit_num <= context.UserSoupValueHis.Where(s => s.UserId == userId && s.TaskType == item.type).Count())
                            item.is_complete = true;
                    }
                }

                ////已开通节点商城的不显示对应任务
                //var openSupplierTask = list.Where(o => o.type == ETaskType.OpenTokenSupplier && o.is_complete == true).FirstOrDefault();
                //if (openSupplierTask != null)
                //    list.Remove(openSupplierTask);
            }
            return list;
        }

        /// <summary>
        /// APP获得任务详情（记录点击数）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public task_dto AppGetSoupTask(long id, long userId, ETaskType type = 0) {
            var member = _iMerchantService.GetTokenUser(userId);
            if (!member.is_verify_no_card) {
                throw new ServerErrorException("请先实名认证");
            }
            task_dto result = null;
            if (type > 0) result = context.SoupTask.Where(o => o.Type == type).FromCacheFirstOrDefault<SoupTask, task_dto>("SoupTask");
            else result = context.SoupTask.Where(o => o.Id == id).FromCacheFirstOrDefault<SoupTask, task_dto>("SoupTask");

            if (result.type == ETaskType.Login) {
                long startTime = DateTime.Now.Date.ToUnixInt();
                bool ishas = context.TokenTaskDayLogin.Exist(s => s.Time == startTime && s.UserId == userId);
                result.is_complete = ishas;
            } else if (result.type == ETaskType.Maker) {
                var taskupgrade = context.TokenTaskUpgrade.Find(userId);
                result.is_complete = (taskupgrade != null && taskupgrade.Status == 2);
                //以下很重要
                result.task_status = (taskupgrade != null && taskupgrade.Status == 1) ? 1 : 2;
            } else if (result.type == ETaskType.MaYiBuLuo) {
                var startTime = DateTime.Now.ToUnixInt();
                bool ishas = context.TokenTaskMayi.Exist(s => s.Time == startTime && s.UserId == userId);
                result.is_complete = ishas;
            } else if (result.type == ETaskType.CreditCard) {
                bool ishas = context.TokenTaskCreditCard.Exist(s => s.UserId == userId && (s.Status == 1 || s.Status == 3));
                result.is_complete = ishas;
            } else if (result.type == ETaskType.ApplyLoan) {
                bool ishas = context.TokenTaskApplyLoan.Exist(s => s.UserId == userId && (s.Status == 1 || s.Status == 3));
                result.is_complete = ishas;
            } else if (result.type == ETaskType.InviteRegister) {
                var redRecod = _redRecordService.GetUser(userId);
                bool ishas = (result.limit_num != null && result.limit_num <= redRecod.invitation_num);
                result.is_complete = ishas;
            } else if (result.type == ETaskType.WatchLive) {
                var startTime = DateTime.Now.Date.ToUnixInt();
                bool ishas = context.TokenTaskWatchLive.Exist(s => s.Time == startTime && s.UserId == userId);
                result.is_complete = ishas;
            } else if (result.type == ETaskType.ViewMall) {
                var startTime = DateTime.Now.Date.ToUnixInt();
                bool ishas = context.TokenTaskViewMall.Exist(s => s.Time == startTime && s.UserId == userId);
                result.is_complete = ishas;
            } else if (result.type == ETaskType.FollowPubAccount) {
                var vx = context.WXVerificationCode.Exist(o => o.UserId == userId);
                result.is_complete = vx;
            } else if (result.type == ETaskType.Auth) {
                result.is_complete = member.is_verify_no_card;
            } else if (result.type == ETaskType.OpenTokenSupplier) {
                var merchant = _iMerchantService.Get(userId);
                result.is_complete = merchant.is_supplier;
            } else {
                if (result.limit_num != null && result.limit_num <= context.UserSoupValueHis.Where(s => s.UserId == userId && s.TaskType == result.type).Count())
                    result.is_complete = true;
            }

            if (userId > 0 && !result.is_complete && (result.type == ETaskType.CreditCard || result.type == ETaskType.ApplyLoan || result.type == ETaskType.CreditCardPointExchange)) {
                if (result.type == ETaskType.CreditCard) {//信用卡申请
                    if (!context.TokenTaskCreditCard.Exist(o => o.UserId == userId)) {
                        var merchant = _iMerchantService.Get(userId);
                        var taskCreditCard = new TokenTaskCreditCard() { UserId = userId, Time = DateTime.Now.ToUnixInt(), Status = 2, Mobile = merchant.mobile };
                        context.TokenTaskCreditCard.Add(taskCreditCard);
                        _iUnitOfWork.Commit();
                    }
                } else if (result.type == ETaskType.ApplyLoan) {//申请贷款
                    if (!context.TokenTaskApplyLoan.Exist(o => o.UserId == userId)) {
                        var merchant = _iMerchantService.Get(userId);
                        var taskApplyLoan = new TokenTaskApplyLoan() { UserId = userId, Time = DateTime.Now.ToUnixInt(), Status = 2, Mobile = merchant.mobile };
                        context.TokenTaskApplyLoan.Add(taskApplyLoan);
                        _iUnitOfWork.Commit();
                    }
                }

                //var resl = TaskRecive(userId, result.type).Result;
            }

            return result;
        }

        /// <summary>
        /// 任务获取马力
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> TaskRecive(long userId, ETaskType taskType, long itemId = 0, string code = "") {
            var member = _iMerchantService.GetTokenUser(userId);
            if (!member.is_verify_no_card) {//实名认证未通过
                throw new ServerErrorException("实名认证未通过，无法领取马力");
            }

            #region MyRegion
            var soupTask = context.SoupTask.Where(s => s.Type == taskType).FirstOrDefault();
            if (soupTask == null) throw new ServerErrorException("没有此任务");
            if (soupTask.Status != ESoupTaskStatus.Normal) throw new ServerErrorException("该任务已停用");
            var red = context.RedRecord.FirstOrDefault(s => s.MerchantId == userId);
            var tags = new List<string>();
            UserSoupValueHis userSoupValueHis = new UserSoupValueHis() { UserId = userId, TaskType = taskType, ItemId = itemId, CreateTime = DateTime.Now.ToUnix() };
            DateTime startTime = DateTime.Now.Date;
            bool ishas = false;
            #region 任务
            switch (taskType) {
                case ETaskType.Login:
                    ishas = TaskLoginHandle(userId, itemId, soupTask, red, userSoupValueHis, startTime, tags);
                    break;
                case ETaskType.Maker:
                    ishas = TaskMakerHandle(userId, soupTask, userSoupValueHis);
                    break;
                case ETaskType.MerchIntroduce:
                    ishas = TaskMerchIntroduceHandle(userId, taskType, itemId, tags, userSoupValueHis);
                    break;
                case ETaskType.MaYiBuLuo:
                    ishas = TaskMaYIBuLuoHandle(userId, itemId, member, soupTask, userSoupValueHis, startTime, tags);
                    break;
                case ETaskType.FollowPubAccount:
                    ishas = TaskFollowPubAccountHandle(userId, taskType, code, soupTask, tags, userSoupValueHis);
                    break;
                case ETaskType.CoinGold:
                    ishas = await TaskCoinGoldHandle(userId, taskType, soupTask, red, userSoupValueHis);
                    break;
                case ETaskType.GeLunBu:
                    ishas = await TaskGeLunBuHandle(userId, taskType, soupTask, red, userSoupValueHis);
                    break;
                case ETaskType.ShiDaiYunShang:
                    ishas = await TaskShiDaiYunShangHandle(userId, taskType, soupTask, red, userSoupValueHis);
                    break;
                case ETaskType.CreditCardApplication:
                    ishas = TaskCreditCardApplicationHandle(userId, taskType, soupTask, userSoupValueHis);
                    break;
                case ETaskType.CreditCard:
                    ishas = TaskCreditCardHandle(userId, taskType, soupTask, userSoupValueHis, tags);
                    break;
                case ETaskType.ApplyLoan:
                    ishas = TaskApplyLoanHandle(userId, taskType, soupTask, userSoupValueHis, tags);
                    break;
                case ETaskType.CreditCardPointExchange:
                    ishas = TaskCreditCardPointExchangeHandle(userId, taskType, soupTask, userSoupValueHis);
                    break;
                case ETaskType.WatchCourse:
                    ishas = TaskWatchCourseHandle(userId, taskType, itemId, userSoupValueHis);
                    break;
                case ETaskType.WatchLive:
                    ishas = TaskWatchLiveHandle(userId, taskType, soupTask, userSoupValueHis, startTime, tags);
                    break;
                case ETaskType.MallShopping:
                    ishas = TaskMallShoppingHandle(userId, taskType, soupTask, itemId, red);//因一笔订单可能需要多条马力记录，子方法内单独记录马力明细和增加马力总数，最后方法外统一提交
                    break;
                case ETaskType.ViewMall:
                    ishas = TaskViewMallHandle(userId, taskType, soupTask, userSoupValueHis, startTime, tags);
                    break;
                case ETaskType.OpenTokenSupplier:
                    ishas = TaskOpenTokenSupplier(userId, taskType, soupTask, userSoupValueHis, red, tags);
                    break;
            }
            #endregion
            int result = 0;
            if (!ishas && userSoupValueHis.SoupValue > 0) {
                context.UserSoupValueHis.Add(userSoupValueHis);
                red.TotalHorsePower = red.TotalHorsePower + userSoupValueHis.SoupValue;
                soupTask.GetNum = soupTask.GetNum + 1;
            }
            tags.Add("RedRecord" + userId);
            if (!ishas) {
                result = _iUnitOfWork.Commit(tags.ToArray());
            }

            return result >= 0;
            #endregion
        }

        /// <summary>
        /// 处理登录任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="itemId"></param>
        /// <param name="soupTask"></param>
        /// <param name="red"></param>
        /// <param name="userSoupValueHis"></param>
        /// <param name="startTime"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private bool TaskLoginHandle(long userId, long itemId, SoupTask soupTask, RedRecord red, UserSoupValueHis userSoupValueHis, DateTime startTime, List<string> tags) {
            bool ishas;
            var taskDayLogin = context.TokenTaskDayLogin.Where(o => o.UserId == userId).FirstOrDefault();
            if (taskDayLogin == null) {
                taskDayLogin = new TokenTaskDayLogin() { UserId = userId };
                context.TokenTaskDayLogin.Add(taskDayLogin);
            }
            ishas = taskDayLogin.Time == DateTime.Now.Date.ToUnixInt();
            if (!ishas) {
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
                taskDayLogin.Time = DateTime.Now.Date.ToUnixInt();
            }
            return ishas;
        }

        /// <summary>
        /// 创客奖励任务
        /// </summary>
        /// <returns></returns>
        private bool TaskMakerHandle(long userId, SoupTask soupTask, UserSoupValueHis userSoupValueHis) {
            bool ishas = true;
            var item = context.TokenTaskUpgrade.Find(userId);
            if (item != null && item.Status == 1) {
                item.Status = 2;
                var dt = DateTime.Now;
                var cdt = dt.ToUnix();
                var effdt = dt.AddDays(soupTask.LimitDay.Value).ToUnix();
                var soup_val = soupTask.SoupValue ?? 1;
                userSoupValueHis.SoupValue = soup_val;
                userSoupValueHis.EffectiveTime = effdt;
                //增加临时表
                context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = userId, TaskType = soupTask.Type, CreateTime = cdt, EffectiveTime = effdt, SoupValue = soup_val });

                ishas = false;
            }
            return ishas;
        }

        /// <summary>
        /// 处理商家介绍任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="itemId"></param>
        /// <param name="tags"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskMerchIntroduceHandle(long userId, ETaskType taskType, long itemId, List<string> tags, UserSoupValueHis userSoupValueHis) {
            bool ishas;
            MerchIntroduce merchIntroduce = context.MerchIntroduce.FindById(itemId);
            ishas = context.UserSoupValueHis.Exist(s => s.UserId == userId && s.TaskType == taskType && s.ItemId == itemId);
            if (ishas)//已经获取过该篇商户介绍的马力值
                throw new ServerErrorException("该任务已领取");
            userSoupValueHis.SoupValue = merchIntroduce.SoupValue;
            merchIntroduce.GetNum = merchIntroduce.GetNum + 1;
            return ishas;
        }

        /// <summary>
        /// 处理蚂蚁部落任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="itemId"></param>
        /// <param name="member"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <param name="startTime"></param>
        /// <returns></returns>
        private bool TaskMaYIBuLuoHandle(long userId, long itemId, token_user_info member, SoupTask soupTask, UserSoupValueHis userSoupValueHis, DateTime startTime, List<string> tags) {
            var mayiTask = context.TokenTaskMayi.Where(o => o.UserId == userId).FirstOrDefault();
            if (mayiTask == null) {
                mayiTask = new TokenTaskMayi() { UserId = userId, DayParentSoupValue = 0 };
                context.TokenTaskMayi.Add(mayiTask);
            }
            bool ishas = mayiTask.Time == startTime.ToUnixInt();
            if (!ishas) {
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
                mayiTask.Time = startTime.ToUnixInt();
                var parent = _iMerchantService.Get(member.parent_id);
                //上级是创客以上的
                //  if (parent.usertype.HasValue && (int)parent.usertype.Value >= (int)UserType.tokenMaker && (int)parent.usertype.Value >= (int)UserType.tokenCityAgent) {
                if (parent.usertype.HasValue && parent.usertype.Value >= UserType.tokenMaker && parent.usertype.Value <= UserType.tokenCityAgent) {
                    var p_soupTask = context.SoupTask.Where(s => s.Type == ETaskType.MaYiParent).FromCacheFirstOrDefault<SoupTask, soup_task_dto>();
                    if (p_soupTask.status == ESoupTaskStatus.Normal) {
                        if (p_soupTask.url.Contains(".")) {
                            var limits = p_soupTask.url.Split('.').Select(c => int.Parse(c));
                            var edt = startTime.AddDays(1);
                            var parentMayi = context.TokenTaskMayi.Where(o => o.UserId == member.parent_id).FirstOrDefault();
                            if (parentMayi == null) {
                                parentMayi = new TokenTaskMayi() { UserId = member.parent_id, DayParentSoupValue = 0, ParentTime = startTime.ToUnixInt() };
                                context.TokenTaskMayi.Add(parentMayi);
                            }
                            if (parentMayi.ParentTime < startTime.ToUnixInt()) {
                                parentMayi.ParentTime = startTime.ToUnixInt();
                                parentMayi.DayParentSoupValue = 0;
                            }
                            int souplimit = parentMayi.DayParentSoupValue;
                            //判断上级当天有没有超过限定的增加马力
                            if ((parent.usertype.Value == UserType.tokenMaker && souplimit < limits.ElementAt(0)) || (parent.usertype.Value == UserType.tokenNodeMall && souplimit < limits.ElementAt(1))
                                || (parent.usertype.Value == UserType.tokenCountyAgent && souplimit < limits.ElementAt(2)) || (parent.usertype.Value == UserType.tokenCityAgent && souplimit < limits.ElementAt(3))) {
                                if (p_soupTask.limit_day.HasValue) {
                                    var dt = DateTime.Now;
                                    var cdt = dt.ToUnix();
                                    var effdt = dt.AddDays(p_soupTask.limit_day.Value).ToUnix();
                                    var p_soup_val = p_soupTask.soup_value ?? 1;
                                    var p_userSoupValueHis = new UserSoupValueHis() { UserId = member.parent_id, TaskType = ETaskType.MaYiParent, CreateTime = cdt, EffectiveTime = effdt, SoupValue = p_soup_val };
                                    parentMayi.DayParentSoupValue += p_soup_val;
                                    var p_red = context.RedRecord.FirstOrDefault(s => s.MerchantId == member.parent_id);
                                    p_red.TotalHorsePower = p_red.TotalHorsePower + p_soup_val;
                                    context.UserSoupValueHis.Add(p_userSoupValueHis);
                                    tags.Add("RedRecord" + p_red.MerchantId);
                                    //增加临时表
                                    context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = member.parent_id, TaskType = ETaskType.MaYiParent, CreateTime = cdt, EffectiveTime = effdt, SoupValue = p_soup_val });

                                }
                            }
                        }
                    }

                }
            }
            return ishas;
        }

        /// <summary>
        /// 处理关注公众号任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="code"></param>
        /// <param name="soupTask"></param>
        /// <param name="tags"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskFollowPubAccountHandle(long userId, ETaskType taskType, string code, SoupTask soupTask, List<string> tags, UserSoupValueHis userSoupValueHis) {
            bool ishas = context.WXVerificationCode.Exist(o => o.UserId == userId);
            if (ishas) throw new ServerErrorException("该任务已领取");
            if (string.IsNullOrEmpty(code)) throw new ServerErrorException("验证码不能为空");
            var wechat = context.WXVerificationCode.FirstOrDefault(s => s.VerificationCode == code);
            if (wechat == null || (wechat.UserId != null && wechat.UserId != userId)) throw new ServerErrorException("验证码不正确");
            userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            userSoupValueHis.ItemId = wechat.Id;
            wechat.UserId = userId;
            return ishas;
        }

        /// <summary>
        /// 处理币金所任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="red"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private async Task<bool> TaskCoinGoldHandle(long userId, ETaskType taskType, SoupTask soupTask, RedRecord red, UserSoupValueHis userSoupValueHis) {
            bool ishas = context.UserSoupValueHis.Exist(s => s.TaskType == taskType && s.UserId == userId);
            if (ishas) throw new ServerErrorException("该任务已领取");
            var obj = new { loginname = red.Merchant.Mobile };
            try {
                var content = new Dictionary<string, string>();

                content.Add("loginname", red.Merchant.Mobile);
                var formUrlContent = new FormUrlEncodedContent(content);
                var data = await t_RequestMethod.bijin_url.PostAsync(formUrlContent).ReceiveJson();
                if (data.code != 200)
                    throw new ServerErrorException("请先注册注册币金所");
            }
            catch {
                throw new ServerErrorException("您还没有达到任务邀请，无法完成任务");
            }
            userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            return ishas;
        }

        /// <summary>
        /// 处理戈伦埠任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="red"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private async Task<bool> TaskGeLunBuHandle(long userId, ETaskType taskType, SoupTask soupTask, RedRecord red, UserSoupValueHis userSoupValueHis) {
            bool ishas = context.UserSoupValueHis.Exist(s => s.TaskType == taskType && s.UserId == userId);
            if (ishas) throw new ServerErrorException("该任务已领取");
            var gobj = new { mobile = red.Merchant.Mobile };
            try {
                var gdata = await t_RequestMethod.gelunbu_url.PostJsonAsync(gobj).ReceiveJson();
                if (!(gdata.result_code == 1000 && gdata.data))
                    throw new ServerErrorException("请先下载并注册戈仑埠");
            }
            catch {
                throw new ServerErrorException("您还没有达到任务邀请，无法完成任务");
            }
            userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            return ishas;
        }

        /// <summary>
        /// 处理时代云商任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="red"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private async Task<bool> TaskShiDaiYunShangHandle(long userId, ETaskType taskType, SoupTask soupTask, RedRecord red, UserSoupValueHis userSoupValueHis) {
            bool ishas = context.UserSoupValueHis.Exist(s => s.TaskType == taskType && s.UserId == userId);
            if (ishas) throw new ServerErrorException("该任务已领取");
            var sobj = new { mobile = red.Merchant.Mobile };
            try {
                var sdata = await t_RequestMethod.shidai_url.PostJsonAsync(sobj).ReceiveJson();
                if (!(sdata.result_code == 1000 && sdata.data))
                    throw new ServerErrorException("请先下载并注册时代云商");
            }
            catch {
                throw new ServerErrorException("您还没有达到任务邀请，无法完成任务");
            }
            userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            return ishas;
        }

        /// <summary>
        /// 处理信用卡申领任务（旧通道）
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskCreditCardApplicationHandle(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis) {
            bool ishas = context.UserSoupValueHis.Exist(s => s.TaskType == taskType && s.UserId == userId);
            if (!ishas) userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            return ishas;
        }

        /// <summary>
        /// 处理申请信用卡任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        private bool TaskCreditCardHandle(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis, List<string> tags) {
            bool ishas = true;
            var taskCreditCard = context.TokenTaskCreditCard.Where(o => o.UserId == userId && o.Status == 2).FirstOrDefault();
            if (taskCreditCard != null) {
                ishas = false;
                taskCreditCard.Status = 3;
                taskCreditCard.UpdateTime = DateTime.Now.ToUnix();
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            }
            return ishas;
        }

        /// <summary>
        /// 处理申请贷款任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskApplyLoanHandle(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis, List<string> tags) {
            bool ishas = true;
            var taskApplyLoan = context.TokenTaskApplyLoan.Where(o => o.UserId == userId && o.Status == 2).FirstOrDefault();
            if (taskApplyLoan != null) {
                ishas = false;
                taskApplyLoan.Status = 3;
                taskApplyLoan.UpdateTime = DateTime.Now.ToUnix();
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            }
            return ishas;
        }

        /// <summary>
        /// 处理信用卡积分兑换任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskCreditCardPointExchangeHandle(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis) {
            bool ishas = context.UserSoupValueHis.Exist(s => s.TaskType == taskType && s.UserId == userId);
            if (!ishas) userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
            return ishas;
        }

        /// <summary>
        /// 处理观看课程任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="itemId"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskWatchCourseHandle(long userId, ETaskType taskType, long itemId, UserSoupValueHis userSoupValueHis) {
            bool ishas;
            Course course = context.Course.FindById(itemId);
            if (course == null || course.IsEnable == false)
                throw new ServerErrorException("该课程未启用");
            ishas = context.UserSoupValueHis.Exist(s => s.UserId == userId && s.TaskType == taskType && s.ItemId == itemId);
            if (ishas)//已经获取过该课程的马力值
                throw new ServerErrorException("该任务已领取");
            userSoupValueHis.SoupValue = course.Horse;
            return ishas;
        }

        /// <summary>
        /// 处理观看直播任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <returns></returns>
        private bool TaskWatchLiveHandle(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis, DateTime startTime, List<string> tags) {
            var watchLive = context.TokenTaskWatchLive.Where(o => o.UserId == userId).FirstOrDefault();
            if (watchLive == null) {
                watchLive = new TokenTaskWatchLive() { UserId = userId };
                context.TokenTaskWatchLive.Add(watchLive);
            }
            bool ishas = watchLive.Time == startTime.ToUnixInt();
            if (!ishas) {
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
                watchLive.Time = startTime.ToUnixInt();
                if (soupTask.LimitDay != null) {//有设置马力有效天数
                    //设置过期时间
                    userSoupValueHis.EffectiveTime = userSoupValueHis.CreateTime.ToDateTime().AddDays(soupTask.LimitDay.Value).ToUnix();
                    //增加临时表
                    context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = userId, TaskType = taskType, CreateTime = userSoupValueHis.CreateTime, EffectiveTime = (long)userSoupValueHis.EffectiveTime, SoupValue = userSoupValueHis.SoupValue });
                }
            }
            return ishas;
        }

        /// <summary>
        /// 处理商城购物马力
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="itemId"></param>
        /// <param name="red"></param>
        /// <returns></returns>
        private bool TaskMallShoppingHandle(long userId, ETaskType taskType, SoupTask soupTask, long itemId, RedRecord red) {
            bool ishas;
            ishas = context.TokenTaskMallShopping.Exist(o => o.Id == itemId);
            if (!ishas) {
                var order = context.Orders.Where(o => o.Id == itemId).FirstOrDefault().ToDtoObject<order_dto>();
                decimal orderAmount = order.order_amount;
                int add_total_horse_power = 0;

                #region 活动商品马力，遍历订单明细 判断商品是否参与活动
                foreach (var order_item in order.order_items) {
                    int act_hourse_hower = 0;
                    int? act_limit_day = null;
                    product_activity_dto pa1 = null;
                    if (order_item.sku_id != null && order_item.sku_id > 0) {//有规格
                        pa1 = _iProductActivityService.GetAvailable(order_item.product_id, order_item.sku_id.Value);
                    } else {//无规格
                        pa1 = _iProductActivityService.GetAvailable(order_item.product_id);
                    }
                    if (pa1 != null && pa1.product_activity_time_buy != null && pa1.product_activity_time_buy.horse_power > 0) {
                        act_hourse_hower = pa1.product_activity_time_buy.horse_power * order_item.quantity;
                        act_limit_day = pa1.product_activity_time_buy.horse_power_effective;
                        orderAmount = orderAmount - (order_item.unit_price * order_item.quantity);
                    }
                    if (act_hourse_hower > 0) {
                        UserSoupValueHis o_usvh = new UserSoupValueHis() { UserId = userId, TaskType = taskType, SoupValue = act_hourse_hower, ItemId = itemId, CreateTime = DateTime.Now.ToUnix() };
                        if (act_limit_day != null && act_limit_day.Value > 0) {
                            //设置过期时间
                            o_usvh.EffectiveTime = o_usvh.CreateTime.ToDateTime().AddDays(act_limit_day.Value).ToUnix();
                            //增加临时表
                            context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = userId, TaskType = taskType, CreateTime = o_usvh.CreateTime, EffectiveTime = (long)o_usvh.EffectiveTime, SoupValue = act_hourse_hower });
                        }
                        add_total_horse_power += o_usvh.SoupValue;
                        context.UserSoupValueHis.Add(o_usvh);
                    }
                }
                #endregion

                #region 扣除活动商品，订单其余部分算金额加马力
                token_mall_shopping_setting shopping_setting = _iSettingService.GetTokenSetting().token_mall_shopping_setting;
                int? limitDay = soupTask.LimitDay;
                int shop_horse_power = 0;
                if (orderAmount >= 1 && orderAmount <= 100)
                    shop_horse_power = shopping_setting.give_horse_power_1;
                else if (orderAmount > 100 && orderAmount <= 200)
                    shop_horse_power = shopping_setting.give_horse_power_2;
                else if (orderAmount > 200 && orderAmount <= 500)
                    shop_horse_power = shopping_setting.give_horse_power_3;
                else if (orderAmount > 500 && orderAmount <= 1000)
                    shop_horse_power = shopping_setting.give_horse_power_4;
                else if (orderAmount > 1000)
                    shop_horse_power = shopping_setting.give_horse_power_5;

                if (shop_horse_power > 0) {
                    UserSoupValueHis userSoupValueHis = new UserSoupValueHis() { UserId = userId, TaskType = taskType, SoupValue = shop_horse_power, ItemId = itemId, CreateTime = DateTime.Now.ToUnix() };
                    if (limitDay != null && limitDay > 0) {//有设置马力有效天数
                        //设置过期时间
                        userSoupValueHis.EffectiveTime = userSoupValueHis.CreateTime.ToDateTime().AddDays(limitDay.Value).ToUnix();
                        //增加临时表
                        context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = userId, TaskType = taskType, CreateTime = userSoupValueHis.CreateTime, EffectiveTime = (long)userSoupValueHis.EffectiveTime, SoupValue = shop_horse_power });
                    }
                    add_total_horse_power += userSoupValueHis.SoupValue;
                    context.UserSoupValueHis.Add(userSoupValueHis);
                }
                #endregion

                TokenTaskMallShopping tokenTaskMallShopping = new TokenTaskMallShopping() { OrderId = itemId, UserId = userId, Time = DateTime.Now.ToUnix() };
                context.TokenTaskMallShopping.Add(tokenTaskMallShopping);

                if (add_total_horse_power > 0) {
                    red.TotalHorsePower = red.TotalHorsePower + add_total_horse_power;
                    soupTask.GetNum = soupTask.GetNum + 1;
                }
            }
            return ishas;
        }

        /// <summary>
        /// 处理浏览商城任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <param name="startTime"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        private bool TaskViewMallHandle(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis, DateTime startTime, List<string> tags) {
            var viewMall = context.TokenTaskViewMall.Where(o => o.UserId == userId).FirstOrDefault();
            if (viewMall == null) {
                viewMall = new TokenTaskViewMall() { UserId = userId };
                context.TokenTaskViewMall.Add(viewMall);
            }
            bool ishas = viewMall.Time == startTime.ToUnixInt();
            if (!ishas) {
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
                viewMall.Time = startTime.ToUnixInt();
                if (soupTask.LimitDay != null) {//有设置马力有效天数
                    //设置过期时间
                    userSoupValueHis.EffectiveTime = userSoupValueHis.CreateTime.ToDateTime().AddDays(soupTask.LimitDay.Value).ToUnix();
                    //增加临时表
                    context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = userId, TaskType = taskType, CreateTime = userSoupValueHis.CreateTime, EffectiveTime = (long)userSoupValueHis.EffectiveTime, SoupValue = userSoupValueHis.SoupValue });
                }
            }
            return ishas;
        }

        /// <summary>
        /// 处理开通拓垦节点商城
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskType"></param>
        /// <param name="soupTask"></param>
        /// <param name="userSoupValueHis"></param>
        /// <param name="red"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        private bool TaskOpenTokenSupplier(long userId, ETaskType taskType, SoupTask soupTask, UserSoupValueHis userSoupValueHis, RedRecord red, List<string> tags) {
            var merchant = context.Merchants.Where(o => o.Id == userId).FirstOrDefault();
            bool ishas = merchant.IsSupplier;
            if (ishas) {
                throw new ServerErrorException("您已开通节点商城");
            } else {
                var setting = _iSettingService.GetTokenSetting().token_open_supplier_setting;
                if (setting == null || setting.open_supplier_red_drill <= 0)
                    throw new ServerErrorException("后台未进行基础设置");
                if ((red.TotalRedDrill - red.ConsumeRedDrill) < setting.open_supplier_red_drill)
                    throw new ServerErrorException("您当前的可用红钻不足");

                //扣除红钻
                red.ConsumeRedDrill += setting.open_supplier_red_drill;
                //红钻消费记录
                RedRecordDetail redRecordDetail = new RedRecordDetail() {
                    MerchantId = userId,
                    HorsePower = 0,
                    RedDrill = setting.open_supplier_red_drill,
                    Type = 7,
                    IsReceive = true,
                    ReceiveTime = DateTime.Now.ToUnix(),
                    CreateTime = DateTime.Now.ToUnix(),
                    RedProductionTime = 0,
                    RedRecordId = red.Id
                };
                context.RedRecordDetail.Add(redRecordDetail);

                //设置为供应商角色
                merchant.IsSupplier = true;

                ////增加店铺表数据
                //if (!context.ShopInfo.Exist(o => o.Id == userId))
                //    context.ShopInfo.Add(new ShopInfo { ShopName = merchant.Name + "节点商城", CreateTime = DateTime.Now.ToUnix(), CustomerTel = merchant.Mobile, Id = userId, Rate = 0.05M });

                //增加马力
                userSoupValueHis.SoupValue = soupTask.SoupValue.HasValue ? soupTask.SoupValue.Value : 0;
                if (soupTask.LimitDay != null) {//有设置马力有效天数
                                                //设置过期时间
                    userSoupValueHis.EffectiveTime = userSoupValueHis.CreateTime.ToDateTime().AddDays(soupTask.LimitDay.Value).ToUnix();
                    //增加临时表
                    context.UserSoupValueSnap.Add(new UserSoupValueSnap { MerchantId = userId, TaskType = taskType, CreateTime = userSoupValueHis.CreateTime, EffectiveTime = (long)userSoupValueHis.EffectiveTime, SoupValue = userSoupValueHis.SoupValue });
                }

                tags.AddRange(new List<string>() { "Merchant" + userId, "Merchant" + merchant.MerchantNo, "RedRecordDetail" + userId, "ShopInfo" + userId });
            }

            return ishas;
        }
    }
}
